package com.hundsun.yr.universal.p2p.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.itemview.SettingView;
import com.hundsun.yr.universal.library.view.itemview.SettingViewItemData;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.MineInvestProtocolBean;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.impl.MineInvestDetailInteractorImpl;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.ItemViewPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseItemView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.List;


/**
 * @version V1.0
 * @Title: MineTransferActivity.java
 * @Description: 我的投资--全部--产品详情
 * @date 2016-1-5 下午4:50:46
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class MineInvestDetailActivity extends BaseActivity implements OnClickListener,
        BaseItemView {

    private RequestPresenter mPresenter = null;
    /**
     * TabRow布局
     **/
    private SettingView setting_view = null;
    /**合同按钮**/
//	private HSButton btn_contract=null;
    /**
     * 到期收益
     **/
    private TextView tv_income = null;
    /**
     * 我的投资详情对象
     **/
    private MyInvestBeen invested = null;
    private TextView tv_income_arrival;
    private HSButton btn_protocol;
    private String zwgt_data;
    private boolean isFirstProtocol = true;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
        invested = (MyInvestBeen) extras.get(Extras.DATA);
    }

    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.act_mine_invest_detail;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void initViewsAndEvents() {
        //初始化设置
        setSystemBarTintDrawable(getResources().getDrawable(R.color.progress_bg_cl));
        toolbar_title.setTextColor(getResources().getColor(R.color.white));
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.progress_bg_cl));
        mToolbar.setNavigationIcon(R.drawable.icon_back_light);
        toolbar_menu.setVisibility(View.GONE);
//        findView(R.id.line_bottom).setVisibility(View.GONE);

        tv_income = findView(R.id.tv_income);
        tv_income_arrival = findView(R.id.tv_income_arrival);

        if (MathUtils.compare(invested.progress, "50") >= 0) {
            tv_income_arrival.setText(getString(R.string.come_income));
        }

        if (MathUtils.compare(invested.progress, "20") >= 0 && MathUtils.compare(invested.progress, "40") <= 0) {
            btn_protocol = findView(R.id.btn_protocol);
            btn_protocol.setVisibility(View.VISIBLE);
            btn_protocol.setOnClickListener(this);
        }

        setting_view = findView(R.id.setting_view);
        mPresenter = new ItemViewPresenterImpl(mContext, this, new MineInvestDetailInteractorImpl());
        mPresenter.initialized();
        setSystemBarTintDrawable(getResources().getDrawable(R.color.loanlist_bg_cl));
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (isFastDoubleClick()) {
            return;
        }

        switch (v.getId()) {
            case R.id.btn_protocol:
                btn_protocol.setEnabled(false);
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                JSONObject map = new JSONObject();
                try {
                    map.put("uuid", invested.uuid);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter.loadingData(TaskConstants.TASK_INVESTPROTOCOL, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_user_test) +
                        TaskConstants.TASK_INVESTPROTOCOL, Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.
                        getString(R.string.api_user_test) + TaskConstants.TASK_INVESTPROTOCOL, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
//                btn_protocol.setEnabled(false);
                break;
        }
    }


    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
        switch (task_name) {
            case TaskConstants.TASK_INVESTPROTOCOL:
                btn_protocol.setEnabled(true);
                AdSlideBeen adSlideBeen = (AdSlideBeen) data;
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.invest_protocol));
//                if (TextUtils.isEmpty(mineInvestProtocolBean.url)) {
//                    bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, mineInvestProtocolBean.html);
//                    bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
//                } else {
                    bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, adSlideBeen.getUrl());
                    bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
//                }
                bundle.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle);
                break;
            case TaskConstants.TASK_INVESTPROHTML:
                MineInvestProtocolBean mineInvestProtocolBean = (MineInvestProtocolBean) data;
                Bundle bundle1 = new Bundle();
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.invest_protocol));
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, mineInvestProtocolBean.getHtml());
                    bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                bundle1.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle1);
                break;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void setAdapter(List<T> data) {
        // TODO 对数据进行赋值
        setting_view.setAdapter((List<SettingViewItemData>) data);
        setToolbarTitle(invested.name);
        if (!invested.rate.isEmpty()) {
            //年化收益率
            setting_view.modifySubTitle(CommTool.keep1Digits(new BigDecimal(invested.rate)) + "%", 0);
        } else {
            setting_view.modifySubTitle(CommTool.keep1Digits(new BigDecimal(0)) + "%", 0);
        }

        //还款方式
        setting_view.modifySubTitle(invested.getPayMethod(mContext), 1);

        //投资金额
        setting_view.modifySubTitle(getString(R.string._yuan, CommTool.keep2Digits(invested.amount)), 2);

        //起息日期
        if (MathUtils.compare(invested.progress, "18") <= 0) {
            setting_view.modifySubTitle(getString(R.string.amount_day), 3);
        } else {
            setting_view.modifySubTitle(invested.start_time, 3);
        }

        if (invested.repayed_term == null || invested.retotal_term == null) {
            if (TextUtils.equals(invested.pay_method, "1")) {
                //已还期数
                setting_view.modifySubTitle(0 + "/" + 1, 4);
            } else {
                setting_view.modifySubTitle(0 + "/" + invested.total_term, 4);
            }
        } else {
            setting_view.modifySubTitle(invested.repayed_term + "/" + invested.retotal_term, 4);
        }


        if (MathUtils.compare(invested.progress, "50") == 0) {
            if (invested.repay_time != null && !invested.repay_time.isEmpty()) {
                //下期还款
                setting_view.modifyTitle(getString(R.string.clear_date2), 5);
                setting_view.modifySubTitle(invested.repay_time, 5);
            } else {
                setting_view.modifyTitle(getString(R.string.clear_date2), 5);
                setting_view.modifySubTitle(invested.end_time, 5);
            }
        }

        if (MathUtils.compare(invested.progress, "20") == 0) {
            setting_view.modifySubTitle(invested.next_repay_day, 5);
        }

        try {
            BigDecimal touZi = new BigDecimal(invested.amount);
            BigDecimal rate = new BigDecimal(invested.rate).divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_EVEN);
            BigDecimal term = new BigDecimal(invested.total_term);
            BigDecimal monthRate = rate.divide(new BigDecimal(12), 10, BigDecimal.ROUND_HALF_EVEN);

            BigDecimal expected_revenue = null;
            switch (invested.pay_method) {
                case "1":
                    //到期还本息付
                    expected_revenue = touZi.multiply(rate).multiply(term).divide(new BigDecimal(360), 5, BigDecimal.ROUND_HALF_EVEN);
                    break;
                case "2":
                    //按月还息到期还本
                    expected_revenue = touZi.multiply(monthRate).multiply(term);
                    break;
                case "3":
                    //等额本息
                    BigDecimal pow = (monthRate.add(new BigDecimal(1))).pow(term.intValue());
                    expected_revenue = (touZi.multiply(monthRate).multiply(pow).divide(pow.subtract(new BigDecimal(1)), 10, BigDecimal.ROUND_HALF_EVEN)).multiply(term).subtract(touZi);
                    break;
                case "4":
                    //等额本金
                    expected_revenue = touZi.multiply(monthRate).multiply((term.add(new BigDecimal(1)))).divide(new BigDecimal(2), 10, BigDecimal.ROUND_HALF_EVEN);
                    break;
            }

            if (MathUtils.compare(invested.progress, "40") <= 0) {
                tv_income.setText(getString(R.string._yuan, CommTool.keep2Digits(expected_revenue.toString())));
            } else {
                if (invested.total_income != null) {
                    tv_income.setText(getString(R.string._yuan, CommTool.keep2Digits(invested.total_income)));
                }
            }

        } catch (Exception e) {
            tv_income.setText("");
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub
        btn_protocol.setEnabled(true);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
